﻿/* jQuery treepicker
 * version: 1.0 (2014-12-09)
 *王柏林
 */
!function ($) {

    var Treepicker = function (element,elementhide, options) {
        var that = this;
        this.element = $(element);
        this.elementhide=$(elementhide)
        this.container = options.container || 'body';
        this.isInput = this.element.is('input');
        this.bootcssVer = this.isInput ? (this.element.is('.form-control') ? 3 : 2) : (this.bootcssVer = this.element.is('.input-group') ? 3 : 2);
        this.hasInput = this.element.find('input').length;
        this.treePosition = options.treePosition || this.element.data('tree-position') || 'bottom-right';
        this._attachEvents();
        this.picker = $((this.bootcssVer == 3) ? TPGlobal.template : DPGlobal.template)
            .appendTo(this.container) // 'body')
            .on({
                click: $.proxy(this.click, this),
                mousedown: $.proxy(this.mousedown, this)
            });
        this.picker.addClass('treepicker-dropdown-' + this.pickerPosition + ' dropdown-menu');
        $(document).on('mousedown', function (e) {
            // Clicked outside the datetimepicker, hide it
            if ($(e.target).closest('.treepicker').length === 0) {
                that.hide();
            }
        });
        this.autoclose = true;
        if ('autoclose' in options) {
            this.autoclose = options.autoclose;
        }
        $.request(options.url,{token:context.token}, function (result) {
            if (result) {
                $.fn.zTree.init($("#tree"), options, result);

            }
            that.zTree = $.fn.zTree.getZTreeObj("tree");
        });
    };

    Treepicker.prototype = {
        constructor: Treepicker,
        selectValue: {},
        _events: [],
        _attachEvents: function () {
            this._detachEvents();
            if (this.isInput) { // single input
                this._events = [
                    [this.element, {
                        focus: $.proxy(this.show, this)
                    }]
                ];
            }
            else {
                this._events = [
                    [this.element, {
                        click: $.proxy(this.show, this)
                    }]
                ];
            }
            for (var i = 0, el, ev; i < this._events.length; i++) {
                el = this._events[i][0];
                ev = this._events[i][1];
                el.on(ev);
            }
        },
        _detachEvents: function () {
            for (var i = 0, el, ev; i < this._events.length; i++) {
                el = this._events[i][0];
                ev = this._events[i][1];
                el.off(ev);
            }
            this._events = [];
        },
        show: function (e) {
            this.picker.show();
            this.height = this.element.outerHeight();

            this.place();
            $(window).on('resize', $.proxy(this.place, this));
            if (e) {
                e.stopPropagation();
                e.preventDefault();
            }
            this.isVisible = true;

        },
        hide: function (e) {
            if (!this.isVisible) return;

            this.picker.hide();
            $(window).off('resize', this.place);
            if (!this.isInput) {
                $(document).off('mousedown', this.hide);
            }
            this.isVisible = false;
        },
        place: function () {
            var index_highest = 0;
            $('div').each(function () {
                var index_current = parseInt($(this).css("zIndex"), 10);
                if (index_current > index_highest) {
                    index_highest = index_current;
                }
            });
            var zIndex = index_highest + 10;

            var offset, top, left, width, height, containerOffset;
            if (this.container instanceof $) {
                containerOffset = this.container.offset();
            } else {
                containerOffset = $(this.container).offset();
            }


            offset = this.element.offset();
            left = offset.left;

            width = this.element.width();
            if (left + 220 > document.body.clientWidth) {
                left = document.body.clientWidth - 220;
            }

            if (this.pickerPosition == 'top-left' || this.pickerPosition == 'top-right') {
                top = offset.top - this.picker.outerHeight();
            } else {
                top = offset.top + this.height;
            }

            top = top - containerOffset.top;
            left = left - containerOffset.left;

            this.picker.css({
                top: top,
                left: left,
                width: width,
                height: '200px',
                overflow: 'auto',
                zIndex: zIndex
            });
        },
        click: function (e) {
            e.stopPropagation();
            e.preventDefault();

            this.selectValue = this.zTree.getSelectedNodes();
            if (this.selectValue && this.selectValue.length > 0) {
                this.selectValue = this.selectValue[0];
                this.zTree.cancelSelectedNode();
                this.element.val(this.selectValue.orgName);
                this.elementhide.val(this.selectValue.id);
                if (this.autoclose) this.hide();
            }
        }

    };
    $.fn.treepicker = function (hide,options) {
        new Treepicker(this, hide,$.extend({}, $.fn.treepicker.defaults, options));
    };
    $.fn.treepicker.defaults = {
        view: {
            dblClickExpand: true
        },
        data: {

            key: {
                children: "children",
                name: "orgName",
                title: "",
                url: "url"
            },
            simpleData: {
                enable: true,
                idKey: "id",//id
                pIdKey: "pId",//pId
                rootPId: 0
            }
        },
        callback: {
            beforeClick: beforeClick
        },
        url: '/sys/org'
    };
    var TPGlobal = {
        template: "<div  class='treepicker'>\
                            <ul id='tree' class='ztree' style='margin-top:0; width:160px;'></ul>\
                       </div>"
    }

    function beforeClick(treeId, treeNode) {
//        return (treeNode && !treeNode.isParent);
    }

}(window.jQuery);